package com.onlineauction.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.onlineauction.entities.Auction;
import com.onlineauction.entities.Item;
import com.onlineauction.helpers.Constants;
import com.onlineauction.helpers.Constants.Category;

public class ManageAuctionServlet extends HttpServlet 
{

	private static final long serialVersionUID = -4198527463061318990L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException 
	{
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute(Constants.USERNAME);

		// user not logged in
		if (username == null) 
		{
			response.sendRedirect("/LoginAccount");
			return;
		}
		
		
		//validating askPrice
		double askPrice = 0.0;
		try {
			askPrice = Double.parseDouble(request.getParameter(Constants.ASK_PRICE));
		} 
		catch (Exception e) {
			askPrice = -1;
		}
		if (askPrice < 0.0) 
		{
			String message = "Please enter a proper asking price for the action";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
			return;
		}
		
		
		//validating itemID
		long itemID = 0;
		try {
			itemID =  Long.parseLong(request.getParameter(Constants.ITEM_ID));
		} catch (Exception e) {}
		if (itemID == 0 ) 
		{
			String message = "illegal item ID.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
			return;
		}
		List<Auction> auctions = Auction.getLiveAuctionsOfItem(itemID);
		if (auctions != null) 
		{	
			if(auctions.size() > 0)
			{
				String message = "No new auctions can be added as the item already has an active Auction. ";
				request.setAttribute(Constants.MESSAGE, message);
				request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
				return;
			}
		}		
		//validating start and end Times
		Date startTime = null;
		try{
			startTime = stringToDate(request.getParameter(Constants.START_TIME));
		}catch(Exception e){
			
		}
		
		boolean usingCurrentTime =false;
		if (startTime == null ) 
		{
			//if start time is null, using the current system time as start time
			startTime = new Date();
			usingCurrentTime = true;
		}
		
		Date endTime = stringToDate(request.getParameter(Constants.END_TIME));
		if (endTime == null ) 
		{
			String message = "End time of an auction cannot be empty.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
			return;
		}
		
		//comparing and validating start and end timestamps
		Calendar startCal = Calendar.getInstance();
    	Calendar endCal = Calendar.getInstance();
    	Calendar currCal = Calendar.getInstance();
    	startCal.setTime(startTime);
    	endCal.setTime(endTime);
    	if(startCal.after(endCal))
    	{
    		String message = "End time cannot be earlier than the start time.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
			return;
    	}
    	
    	if (!usingCurrentTime)
    	{
	    	if(startCal.before(currCal))
	    	{
	    		String message = "start time cannot be earlier than the current time.";
				request.setAttribute(Constants.MESSAGE, message);
				request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
				return;
	    	}
    	}

    	if(startCal.equals(endCal))
    	{
    		String message = "start and end times cannot be the same.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
			return;
    	}
		

		Auction auction = new Auction(itemID, askPrice, startTime, endTime, true, true);
		String message = "Auction added successfully. <br> If you cannot see it in the Active Auction section yet, please hit <a href=\"/manageAuction.jsp?"+Constants.ITEM_ID+"="+itemID+"\""+"><button>Refresh</button></a>";
		
		request.setAttribute(Constants.MESSAGE, message);
		request.getRequestDispatcher("/manageAuction.jsp").forward(request, response);
		return;

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}
	
	
	public static Date stringToDate(String dateInString)
	{
		//String dateInString = "6/13/2013 13:23";
		SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date date = null;
		try 
		{
			date = (Date) dateFormatter.parse(dateInString);
		} 
		catch (ParseException e) 
		{}
		return date;
	}
}
